package com.crocodileQ.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.crocodileQ.common.AppException;
import com.crocodileQ.domain.entity.LoginUser;
import com.crocodileQ.domain.entity.User;
import com.crocodileQ.enums.AppExceptionMsgEnum;
import com.crocodileQ.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);

        User user = userMapper.selectOne(queryWrapper);

        if(BeanUtil.isEmpty(user)){
            throw new AppException(AppExceptionMsgEnum.REQUIRED_USERNAME);
        }

        //返回用户信息
        return new LoginUser(user);
    }
}
